import requests
import json

# 第一个 API 的配置
url1 = "https://api.mianshiya.com/api/question_bank/list/page/vo"
data1 = {
    "current": 1,
    "pageSize": 2000
}
data1 = json.dumps(data1, separators=(',', ':'))

# 第二个 API 的配置
url2 = "https://api.mianshiya.com/api/question_bank/list_question"
headers = {
    "accept": "*/*",
    "accept-language": "zh-CN,zh;q=0.9",
    "content-type": "application/json",
    "origin": "https://www.mianshiya.com",
    "priority": "u=1, i",
    "referer": "https://www.mianshiya.com/",
    "sec-ch-ua": "\"Not)A;Brand\";v=\"99\", \"Google Chrome\";v=\"127\", \"Chromium\";v=\"127\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-site",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"
}
cookies = {
    "Hm_lvt_8abb85f1b5cfd5f406cdcc6454141898": "1740034256",
    "HMACCOUNT": "9798B0F0E3BE761A",
    "Hm_lvt_c7cedf2eca8990b32ef9f1a0412e7102": "1740034256",
    "Hm_lpvt_c7cedf2eca8990b32ef9f1a0412e7102": "1740034267",
    "Hm_lpvt_8abb85f1b5cfd5f406cdcc6454141898": "1740034267"
}

# 第一步：调用第一个 API，提取 id 和 title
response1 = requests.post(url1, headers=headers, cookies=cookies, data=data1)
if response1.status_code != 200:
    print(f"第一个 API 请求失败，状态码：{response1.status_code}")
    exit()

# 解析第一个 API 的响应数据
response_data1 = response1.json()
records = response_data1.get('data', {}).get('records', [])
if not records:
    print("第一个 API 未返回有效数据")
    exit()

# 遍历 records，提取 id 和 title
for record in records:
    question_bank_id = record.get('id')
    title = record.get('title')
    if not question_bank_id or not title:
        continue

    # 第二步：调用第二个 API，使用 question_bank_id 作为参数
    current_page = 1
    all_titles = []

    while True:
        data2 = {
            "current": current_page,
            "pageSize": 20,
            "questionBankId": question_bank_id,
            "tagList": []
        }
        data2 = json.dumps(data2, separators=(',', ':'))
        response2 = requests.post(url2, headers=headers, cookies=cookies, data=data2)

        # 检查响应状态码
        if response2.status_code != 200:
            print(f"第二个 API 请求失败，状态码：{response2.status_code}")
            break

        # 解析第二个 API 的响应数据
        response_data2 = response2.json()

        # 检查是否有数据
        records2 = response_data2.get('data', {}).get('records', [])
        if not records2:
            break

        # 提取当前页的 title 并添加到总列表中
        for record2 in records2:
            title2 = record2.get('title')
            if title2:
                all_titles.append(title2)

        # 增加页码
        current_page += 1

    # 将提取的 title 写入文件
    file_name = f"{title}.txt"
    with open(file_name, 'w', encoding='utf-8') as f:
        for title2 in all_titles:
            f.write(title2 + '\n')

    print(f"数据已成功写入 {file_name} 文件")